package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"rbac/cache"
	"rbac/models"
	"rbac/pkg"
	"strconv"
	"time"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户名 或者 密码为空",
		}
		c.ServeJSON()
		return
	}

	loginErrorKey := "login_error" + username
	errorCount, _ := cache.Rdb.Get(cache.Ctx, loginErrorKey).Int()
	if errorCount >= 3 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "密码错误三次禁止登录",
		}
		c.ServeJSON()
		return
	}

	var err error
	var user models.User
	err = models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户不存在",
		}
		c.ServeJSON()
		return
	}

	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, loginErrorKey) //密码错误一次，错误值+1
		if errorCount == 2 {
			cache.Rdb.Set(cache.Ctx, loginErrorKey, 3, time.Hour*2) //密码错误3次，封禁2个小时
			c.Data["json"] = map[string]interface{}{
				"code": 500,
				"msg":  "密码错误3次，禁止登录",
			}
			c.ServeJSON()
			return
		}

		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "密码错误",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": user,
		"msg":  "登录成功",
	}
	c.ServeJSON()
	return

}

func (c *UserController) RoleNodeAdd() {
	rid, _ := c.GetInt("rid", 0) //角色id
	nid, _ := c.GetInt("nid", 0) //权限id
	if rid == 0 && nid == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "角色ID 或者 权限ID 为空",
		}
		c.ServeJSON()
		return
	}

	data := models.RoleNodeRelation{
		Nid: nid,
		Rid: rid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
	return
}

func (c *UserController) UserRole() {
	uid, _ := c.GetInt("uid", 0) //用户uid
	if uid == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户uid为空",
		}
		c.ServeJSON()
		return
	}

	var Role []models.Role
	err := models.DB.Table("roles").
		Joins("left join user_role_relations on user_role_relations.rid = roles.id").
		Where("user_role_relations.uid = ?", uid).
		Find(&Role).Error

	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "查询失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": Role,
		"msg":  "查询成功",
	}
	c.ServeJSON()
	return

}

func (c *UserController) RoleNode() {
	rid, _ := c.GetInt("rid", 0) //角色uid
	if rid == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "角色rid为空",
		}
		c.ServeJSON()
		return
	}

	var Node []models.Node
	err := models.DB.Table("nodes").
		Joins("left join role_node_relations on role_node_relations.nid = nodes.id").
		Where("role_node_relations.rid = ?", rid).
		Find(&Node).Error

	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "查询失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": Node,
		"msg":  "查询成功",
	}
	c.ServeJSON()
	return

}

func (c *UserController) RoleAdd() {

	role_name := c.GetString("role_name")
	if role_name == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "角色名称为空",
		}
		c.ServeJSON()
		return
	}

	data := models.Role{
		RoleName: role_name,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
	return
}

func (c *UserController) UserAdd() {
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户账户 或者 密码为空",
		}
		c.ServeJSON()
		return
	}
	rid, _ := c.GetInt("rid", 0) //角色id
	if rid == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "角色id为空",
		}
		c.ServeJSON()
		return
	}

	//添加用户
	data := models.User{
		Username: username,
		Password: pkg.Md5Str(password),
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}
	//查询用户的uid
	var user models.User
	err = models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户查询失败",
		}
		c.ServeJSON()
		return
	}

	//添加用户和角色的关系
	relationData := models.UserRoleRelation{
		Uid: int(user.ID),
		Rid: rid,
	}
	err = models.DB.Create(&relationData).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "ok",
	}
	c.ServeJSON()
	return

}

func (c *UserController) UserList() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 2)
	offset := (page - 1) * size

	var err error
	var user []models.User

	listKey := "list_page_" + strconv.Itoa(page)
	cacheList, _ := cache.Rdb.Get(cache.Ctx, listKey).Result()
	if cacheList == "" {
		err = models.DB.Table("users").Limit(size).Offset(offset).Find(&user).Error
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"code": 500,
				"msg":  "数据查询失败",
			}
			c.ServeJSON()
			return
		}
		cacheData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, listKey, cacheData, time.Hour*2)
	} else {
		err = json.Unmarshal([]byte(cacheList), &user)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"code": 500,
				"msg":  "数据查询失败",
			}
			c.ServeJSON()
			return
		}
	}

	var count int64
	models.DB.Table("users").Count(&count)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": map[string]interface{}{
			"list":  user,
			"count": count,
		},
		"msg": "查询成功",
	}
	c.ServeJSON()
	return

}

func (c *UserController) UserDel() {
	id, _ := c.GetInt("id")
	if id == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户id为空",
		}
		c.ServeJSON()
		return
	}
	if err := models.DB.Delete(&models.User{}, id).Error; err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除错误",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 500,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return
}

func (c *UserController) UserDetail() {
	id, _ := c.GetInt("id")
	if id == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户id为空",
		}
		c.ServeJSON()
		return
	}

	////删除redis缓存
	//key := "detail_" + strconv.Itoa(id)
	//cache.Rdb.Del(cache.Ctx, key)

	var user models.User

	key := "detail_" + strconv.Itoa(id)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if cacheData == "" {
		if err := models.DB.Where("id = ?", id).First(&user).Error; err != nil {
			c.Data["json"] = map[string]interface{}{
				"code": 500,
				"msg":  "查询失败",
			}
			c.ServeJSON()
			return
		}
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour*2)
	} else {
		if err := json.Unmarshal([]byte(cacheData), &user); err != nil {
			c.Data["json"] = map[string]interface{}{
				"code": 500,
				"msg":  "数据查询失败",
			}
			c.ServeJSON()
			return
		}
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": user,
		"msg":  "查询成功",
	}
	c.ServeJSON()
	return

}

func (c *UserController) CacheTest() {
	key := "cache_test"

	//添加缓存
	data := models.User{
		Username: "333",
		Password: pkg.Md5Str("333"),
	}
	models.DB.Create(&data)
	var user models.User
	models.DB.Where("username = ?", data.Username).First(&user)
	cacheData, _ := json.Marshal(user)
	cache.Rdb.Set(cache.Ctx, key, cacheData, time.Hour*2) //设置添加缓存

	////删除缓存
	cache.Rdb.Del(cache.Ctx, key) //删除缓存

	//更新缓存
	cache.Rdb.Del(cache.Ctx, key) //删除缓存
	dataNew := models.User{
		Username: "444",
		Password: pkg.Md5Str("444"),
	}
	cacheDataNew, _ := json.Marshal(dataNew)
	cache.Rdb.Set(cache.Ctx, key, cacheDataNew, time.Hour*2) //设置添加缓存

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
	return

}

func (c *UserController) Dat() {

	/*
		       #两表
				  SELECT
					*
				  from nodes
				  LEFT JOIN role_node_relations on role_node_relations.nid=nodes.id;

				#三表
				  SELECT
					*
				  from nodes
				  LEFT JOIN role_node_relations on role_node_relations.nid=nodes.id
				  LEFT JOIN roles on roles.id=role_node_relations.rid;

			   #五表
				SELECT
				  `nodes`.`id`,
				  `nodes`.`created_at`,
				  `nodes`.`updated_at`,
				  `nodes`.`deleted_at`,
				  `nodes`.`node_name`
				FROM
				  `nodes`
				  LEFT JOIN role_node_relations ON role_node_relations.nid = nodes.id
				  LEFT JOIN roles ON roles.id = role_node_relations.rid
				  LEFT JOIN user_role_relations ON user_role_relations.rid = roles.id
				  LEFT JOIN users ON users.id = user_role_relations.uid
				WHERE
				  users.id = 1
				  AND `nodes`.`deleted_at` IS NULL;
	*/
	models.DB.Table("nodes").
		Joins("left join role_node_relations on role_node_relations.nid=nodes.id").
		Joins("left join roles on roles.id=role_node_relations.rid").
		Joins("left join user_role_relations on user_role_relations.rid=roles.id").
		Joins("left join users on users.id=user_role_relations.uid").
		Where("users.id=1").
		Debug().
		Find(&models.Node{})

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
	return

}
